package ar.edu.utn.frsf.cidisi.upcolbpip.verification;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.ProcessBuilder.Redirect;
import java.util.Date;
import java.util.List;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.common.util.WrappedException;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import ar.edu.utn.frsf.cidisi.upcolbpip.UPColBPIPModel;
import ar.edu.utn.frsf.cidisi.upcolbpip.collaborativebusinessprocesses.CollaborativeBusinessProcess;
import ar.edu.utn.frsf.cidisi.upcolbpip.interactionprotocols.InteractionProtocol;
import ar.edu.utn.frsf.cidisi.upcolbpip.presentation.UpcolbpipEditorPlugin;
import ar.edu.utn.frsf.cidisi.upcolbpip2pn.generator.petrinet.Upcolbpip2PN;

/**
 * @generated
 */
public class UpcolbpipVerifyInteractionProtocolAction implements IObjectActionDelegate {

	private static String TARGETDIR = "";

	/**
	 * @generated
	 */
	private IWorkbenchPart targetPart;

	/**
	 * @generated
	 */
	private URI domainModelURI;

	/**
	 * @generated
	 */
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		this.targetPart = targetPart;
	}

	/**
	 * @generated
	 */
	public void selectionChanged(IAction action, ISelection selection) {
		domainModelURI = null;
		action.setEnabled(false);
		if (selection instanceof IStructuredSelection == false
				|| selection.isEmpty()) {
			return;
		}
		IFile file = (IFile) ((IStructuredSelection) selection)
				.getFirstElement();
		domainModelURI = URI.createPlatformResourceURI(file.getFullPath()
				.toString(), true);
		action.setEnabled(true);
	}

	/**
	 * @generated
	 */
	private Shell getShell() {
		return targetPart.getSite().getShell();
	}

	/**
	 * @generated
	 */
	public void run(IAction action) {
		
		
		EObject diagramRoot = null;
		try {
			// Create a resource set
			//
			ResourceSet resourceSet = new ResourceSetImpl();

			Resource resource = resourceSet.getResource(domainModelURI, true);
			diagramRoot = (EObject) resource.getContents().get(0);
		} catch (WrappedException ex) {
			UpcolbpipEditorPlugin.INSTANCE.getPluginLogger().log(
					"Unable to load resource: " + domainModelURI + "\n" + ex); //$NON-NLS-1$
		}
		if (diagramRoot == null) {
//			MessageDialog
//					.openError(
//							getShell(),
//							Messages.UpcolbpipInitDiagramFileAction_InitDiagramFileResourceErrorDialogTitle,
//							Messages.UpcolbpipInitDiagramFileAction_InitDiagramFileResourceErrorDialogMessage);
			return;
		}
		
		if (diagramRoot instanceof UPColBPIPModel){
			
			CollaborativeBusinessProcess cbp = ((UPColBPIPModel)diagramRoot).getB2bCollaboration().getProcesses().get(0);
			
			List<InteractionProtocol> ips = cbp.getInteractionProtocols();
			int size = ips.size();
			
			ProcessBuilder builder;
			Process p;
			try {
				builder = new ProcessBuilder("cmd.exe", "/c", "cls");
				p = builder.start();
			} catch (IOException e2) {
				e2.printStackTrace();
			}

	        System.out.println();
	        System.out.println();
			System.out.println("*****************************************************************");
			System.out.println("*                      Start Verification                       *");
			System.out.println("*****************************************************************");
			System.out.print("PNC Id"+"\t"+"States"+"\t"+"Arcs"+"\t"+
					"Dead states"+"\t"+"Deadlock"+"\t"+"Deadlock state"+"\t"+
					"Dead Transition"+"\t"+"Dead nodes"+"\t"+"Sound"+"\t"+"Verification Time [ms]"+"\t"+"Total Time [s]");
			
			for (int i=0;i<size;i++){
					
				InteractionProtocol ip = ips.get(i);
				
				int elementsCount = elementsCount(ip);
			
				String fileName = ResourcesPlugin.getWorkspace().getRoot().getLocation() +
						domainModelURI.trimFileExtension().toPlatformString(true) +
						ip.getName() + ".cpn";
				
				System.out.print("\n");
				System.out.print(ip.getName()+"\t");
				
				Date startTime = new Date();				

				// Creates the GI-Net that formalizes the interaction protocol ip.-
				createPN(ip,fileName);
	
				fileName = fileName.replace("/", "\\");
				// Starts the state space generator.- 
				GetStateSpaceGenerator h = new GetStateSpaceGenerator(fileName);
				Thread t = new Thread(h);
				t.start();
				
//				try {
//					// Waits until the state space generator finishes its execution.-
//					t.join();
////					System.out.println("Dead thread!!");
//				} catch (InterruptedException e1) {
//					e1.printStackTrace();
//				}
//				
//	            try {
//					System.out.println("Killing cpnmld");
//					
//					ProcessBuilder builder = new ProcessBuilder(
//					        "cmd.exe", "/c", "taskkill /T /F /FI \"IMAGENAME eq cpnmld*\"");
//					
//					Process p = builder.start();
//
//		            System.out.println("Killing conhost");
//					builder = new ProcessBuilder(
//				            "cmd.exe", "/c", "taskkill /T /F /FI \"IMAGENAME eq conhost*\"");
//			        p = builder.start();
//
//	            } catch (IOException e) {
//					e.printStackTrace();
//				}
		
				try{
					Thread.sleep(1500);
//					System.out.println("Starting CPN Tools");
					
					fileName = fileName.replace("/", "\\");
					builder = new ProcessBuilder("cmd.exe", "/c", "call \""+fileName+"\"");
			        p = builder.start();
			        
					try {
						// Waits until the state space generator finishes its execution.-
						t.join();
//						System.out.println("Dead thread!!");
					} catch (InterruptedException e1) {
						e1.printStackTrace();
					}
				        
	
//		            System.out.println("Killing cpn tools");
			        builder = new ProcessBuilder(
				            "cmd.exe", "/c", "taskkill /T /F /FI \"IMAGENAME eq cpntools*\"");
			        p = builder.start();
	
//		            System.out.println("Killing cpnmld");
					builder = new ProcessBuilder(
				            "cmd.exe", "/c", "taskkill /T /F /FI \"IMAGENAME eq cpnmld*\"");
			        p = builder.start();
	
//		            System.out.println("Killing conhost");
					builder = new ProcessBuilder(
				            "cmd.exe", "/c", "taskkill /T /F /FI \"IMAGENAME eq conhost*\"");
			        p = builder.start();
	
//		            System.out.println("Killing run.x86-cygwin");
					builder = new ProcessBuilder(
				            "cmd.exe", "/c", "taskkill /T /F /FI \"IMAGENAME eq run.x86-cygwin*\"");
			        p = builder.start();
				}
				catch (Exception e){
					e.printStackTrace();
				}
				
				Date endTime = new Date();	
				// print time
				System.out.print((endTime.getTime()-startTime.getTime())/1000);

				
			}
			
	        System.out.print("\n");
			System.out.println("*****************************************************************");
			System.out.println("*                        End Verification                       *");
			System.out.println("*****************************************************************");

			//			MessageDialog
//			.openInformation(
//					getShell(),
//					"UP-ColBPIP",
//					"Petri Net specification was generated on " + ip.getName());
		}
		
	}
	
	private void createPN(InteractionProtocol ip, String file) {
		Upcolbpip2PN upcolbpip2PN = new Upcolbpip2PN();
		FileWriter output;
		BufferedWriter writer;

		try {
			
//			output = new FileWriter(TARGETDIR + ResourcesPlugin.getWorkspace().getRoot().getLocation()+"/VMI Collaboration/Verification/" + ip.getName() + ".cpn");
			output = new FileWriter(TARGETDIR + file);
			writer = new BufferedWriter(output);
			writer.write(upcolbpip2PN.generate(ip));
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private int elementsCount(InteractionProtocol ip){
		int elementsCount = 0;
		
		
		return elementsCount;
	}
	
}
